﻿Imports System
Imports System.Runtime.InteropServices
Imports System.IO.Ports
Imports System.Threading
Imports System.Xml
Imports System.Xml.Linq
Imports System.IO
Imports System.Reflection
Imports System.Linq
Imports System.Text
Imports System.ComponentModel
Imports System.Drawing


Public Class Form1

    Public Const debugEnabled As Boolean = False
    Public xmldoc As XDocument = XDocument.Load(New StreamReader([Assembly].GetEntryAssembly.GetManifestResourceStream("WindowsApplication1.Krackerelements.xml")))
    Public WithEvents PropSerial As New PropIO(Me) With {.RXKrackerFWControl = Me.Label15, .xmldoc = Me.xmldoc}
    Public Const newscreen = Chr(16)
    Public Const newline = Chr(13)
    Public diagnostictrl As New DiagnosticControl

    Public picturearray = New List(Of PropertyPairs)

    'Serial Command Strings
    Public Const SOff = "seroff"

    Public MyControlArray As New ButtonArray(Me.Panel2)
    Private WithEvents diagnosticBG As New BackgroundWorker


    Shared fileselected As String
    Shared selectedptr As IntPtr
    Shared updating As Integer = 0
    Delegate Sub SetSerialCallback(ByVal str As String)
    Delegate Sub SetTextCallback(ByVal rowind As Integer, ByVal text As String, ByVal text2 As String, ByVal text4 As String, ByVal text4 As String)

    Private Sub comping(ByVal newstate As Byte) Handles PropSerial.ConnectionStateChanged

        Select Case newstate
            Case PropIO.ConnectionStates.OtherFW
                LinkLabel1.Enabled = True
            Case PropIO.ConnectionStates.Connecting
                LinkLabel1.Enabled = True
            Case PropIO.ConnectionStates.KrackerFW
                LinkLabel1.Enabled = True
                updatedrops()

        End Select

    End Sub

    Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        'Dim newmarg As New MARGINS With {.Top = -1, .bottom = -1, .right = -1, .left = -1}
        'GlassHelper.ExtendGlassFrame(Me, newmarg)
    End Sub


    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        loaddefaults()
        loadimg(picturearray)
        'PropSerial.init()
        PropSerial.loaddrops()
        'TabPage6.Enabled = False
    End Sub
    Private Sub loaddefaults()
        picturearray = New List(Of PropertyPairs) From {New PropertyPairs With {.Name = "WindowsApplication1.kracker_banner.bmp", .Value = Me.PictureBox1}, _
                                                       New PropertyPairs With {.Name = "WindowsApplication1.advanced.bmp", .Value = Me.PictureBox2}, _
                                                       New PropertyPairs With {.Name = "WindowsApplication1.diagnostics.bmp", .Value = Me.PictureBox3}, _
                                                       New PropertyPairs With {.Name = "WindowsApplication1.music.bmp", .Value = Me.PictureBox4}, _
                                                       New PropertyPairs With {.Name = "WindowsApplication1.performancelogging.bmp", .Value = Me.PictureBox5}}


        Me.Height = Me.Height - 15
        With TabControl1
            .Height = TabControl1.Height - 15
            .ItemSize = New Drawing.Size(0, 1)
            '.DrawMode = TabDrawMode.OwnerDrawFixed
            .DrawMode = TabDrawMode.OwnerDrawFixed
            .SizeMode = TabSizeMode.Fixed
        End With
        AddHandler TabControl1.DrawItem, AddressOf TabControl1_DrawItem

 

        TabPage5.Enabled = False
    End Sub



    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Me.Cursor = System.Windows.Forms.Cursors.Default


        Try
            PropellentDLL.QuitProp()
        Catch ex As SEHException
            Console.WriteLine(ex.ErrorCode.ToString)
        End Try

        Thread.Sleep(300)
    End Sub

    Private Function loadimg(files As List(Of PropertyPairs))
        For i As Integer = 0 To files.Count - 1
            Dim target As Object = files.Item(i).Value
            Dim file As String = files.Item(i).Name
            Dim tgtframe As PictureBox = CType(target, PictureBox)
            Dim executing_assembly As System.Reflection.Assembly = Assembly.GetEntryAssembly()
            Dim picture_stream As Stream
            Dim bm As Bitmap
            picture_stream = executing_assembly.GetManifestResourceStream(file)
            If Not (picture_stream Is Nothing) Then
                bm = New Bitmap(picture_stream)
                tgtframe.Image = bm
                picture_stream.Close()
            End If
        Next

        Return 0
    End Function

#Region "Firmware Updates"

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        OpenFileDialog1.ShowDialog()
        fileselected = OpenFileDialog1.FileName()
        Filenamelabel.Text = fileselected
    End Sub
    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        selectedptr = Marshal.StringToHGlobalAnsi(fileselected)
        If SerialPort1.IsOpen Then
            SerialPort1.Close()
        End If

        Label15.Text = "Not Connected"
        updating = 1
        PropellentDLL.flashProp(fileselected, 1)
        Button4.Enabled = False
        Button3.Enabled = False
        PropSerial.reconnect()
        updating = 0

    End Sub
    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        selectedptr = Marshal.StringToHGlobalAnsi(fileselected)
        If SerialPort1.IsOpen Then
            SerialPort1.Close()
        End If
        Label15.Text = "Not Connected"
        updating = 1
        PropellentDLL.flashProp(selectedptr, 3)
        Button4.Enabled = False
        Button3.Enabled = False
        PropSerial.reconnect()
        updating = 0
        'setdebugstrings()
    End Sub
    Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
        Button4.Enabled = True
        Button3.Enabled = True
    End Sub

    Private Sub TabPage4_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TabPage4.Enter
        Button4.Enabled = False
        Button3.Enabled = False
    End Sub

#End Region


#Region "Serial Port Management"
    Private Sub resetDTR()
        Try
            PropSerial.reconnect()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub


    Private Sub updatedrops()
        'Debugger.Break()
        Dim ctl As Control = Me.GetNextControl(Me, True) 'Get the first control in the tab order.
        Do Until ctl Is Nothing
            Dim sent As Type = ctl.GetType
            Dim noloadtag As String = ctl.Tag
            Dim sentarg As String = sent.Name
            If noloadtag <> "noload" Then
                Select Case sentarg
                    Case "RadioButton"
                        RadiobuttonLoad(ctl, New System.EventArgs())
                    Case "ComboBox"
                        comboboxload(ctl, New System.EventArgs())
                    Case "CheckBox"
                        checkboxload(ctl, New System.EventArgs())
                    Case "GroupBox", "TabControl", "LinkLabel", "TextBox", "FlowLayoutPanel"
                        ctl.Enabled = True
                End Select

                If sentarg = "Button" Or sentarg = "TextBox" Or sentarg = "LinkLabel" Then
                    Select Case noloadtag
                        Case "Step1"
                            AddHandler ctl.Click, AddressOf Me.ToTab1
                        Case "Step2"
                            AddHandler ctl.Click, AddressOf Me.ToTab2
                        Case "Step3"
                            AddHandler ctl.Click, AddressOf Me.ToTab3
                        Case "Step4"
                            AddHandler ctl.Click, AddressOf Me.ToTab4
                        Case "Step6"
                            AddHandler ctl.Click, AddressOf Me.ToTab6
                        Case "Step7"
                            AddHandler ctl.Click, AddressOf Me.ToTab7
                        Case "Step8"
                            AddHandler ctl.Click, AddressOf Me.ToTab8
                        Case "Step9"
                            AddHandler ctl.Click, AddressOf Me.ToTab9
                        Case "Step14"
                            AddHandler ctl.Click, AddressOf Me.ToTab14
                    End Select
                End If
            End If
            ctl = Me.GetNextControl(ctl, True) 'Get the next control in the tab order.
        Loop
    End Sub




    Public Function gettext(ByVal controlsel As Integer) As String
        Dim str As String = Nothing
        PropSerial.SerialLineOut("Gs" & controlsel)
        str = PropSerial.SerialLineIn()
        'SerialPort1.DiscardInBuffer()
        Return str
    End Function


#End Region


    Private Sub Button8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button8.Click
        ComboBox46.AccessibleName = ""
        rundiagrequest()

    End Sub

    'Tab Constants
    Public Const TabMain = "TabPage1"
    Public Const TabDiag = "TabPage3"
    Public Const TabLog = "TabPage6"
    Public Const TabRemap = "TabPage2"
    Public Const TabMusic = "TabPage9"
    Public Const TabBT = "TabPage5"
    Public Const TabBusmon = "TabPage7"
    Public Const TabFW = "TabPage4"
    Public Const TabStat = "TabPage8"
    Public Const TabDebug = "TabPage14"

    'Public Sub loaddrops()
    '    Dim activedrop As String = Nothing
    '    Dim activetab As String = Nothing
    '    Dim ob As Object = Nothing

    '    Dim dropsquery = From dropitem In xmldoc.<config>.<dropdowns>.<list>
    '    For Each dropitem In dropsquery
    '        activetab = dropitem.Attribute("page").Value
    '        activedrop = dropitem.Attribute("name").Value

    '        Dim controltest() As Control = Me.Controls.Find(activedrop, True)
    '        If controltest(0) IsNot Nothing Then
    '            ob = controltest(0)
    '            ob.text = dropitem.<label>.Value
    '            ToolTip1.SetToolTip(ob, dropitem.<tooltip>.Value)


    '            If dropitem.Attribute("linkedlist") IsNot Nothing Then
    '                Dim linkedlistname As String = dropitem.Attribute("linkedlist").Value
    '                Dim subdropquery = From duplist In xmldoc.<config>.<selectionlists>.<list> Where _
    '                                   duplist.@name = linkedlistname
    '                ob.text = subdropquery.<label>.Value

    '                If ToolTip1.GetToolTip(ob) = "" Then
    '                    ToolTip1.SetToolTip(ob, subdropquery.<tooltip>.Value)
    '                End If

    '                For Each duplist In subdropquery.<listitems>.<selectable>
    '                    If duplist.Attribute("value") IsNot Nothing Then
    '                        ob.items.add(New clCombobox(duplist.Value, duplist.Attribute("value").Value))
    '                    Else
    '                        ob.items.add(duplist.Value)
    '                    End If

    '                Next
    '            Else
    '                For Each listelement In dropitem.<listitems>.<selectable>
    '                    If listelement.Attribute("value") IsNot Nothing Then
    '                        ob.Items.Add(New clCombobox(listelement.Value, listelement.Attribute("value").Value))

    '                    Else
    '                        ob.Items.add(listelement.Value)
    '                    End If


    '                Next

    '            End If
    '        End If

    '    Next
    'End Sub




    Private Sub TabControl1_deSelecting(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TabControlCancelEventArgs) Handles TabControl1.Deselecting
        If e.TabPage.Name = "TabPage7" And SerialPort1.IsOpen Then
            RemoveHandler SerialPort1.DataReceived, AddressOf SerialPort1_busmon
            PropSerial.SerialLineOut("seroff")
            Thread.Sleep(50)
            Do While SerialPort1.BytesToRead > 0
                SerialPort1.DiscardInBuffer()
            Loop
        ElseIf e.TabPage.Name = "TabPage8" And SerialPort1.IsOpen Then
            RemoveHandler SerialPort1.DataReceived, AddressOf SerialPort1_portdisplay
            SerialPort1.Close()
            PropSerial.reconnect()
        ElseIf e.TabPage.Name = "TabPage3" And SerialPort1.IsOpen Then
            MyControlArray.removeall()
            PropSerial.SerialLineOut("Mx")
            Thread.Sleep(50)
            Do While SerialPort1.BytesToRead > 0
                SerialPort1.DiscardInBuffer()
            Loop
        ElseIf e.TabPage.Name = "TabPage9" Then
            If RadioButton6.Checked = True Then
                RadioButton12.Checked = True
                RadioButton13.Checked = False
            End If
            If RadioButton5.Checked = True Then
                RadioButton13.Checked = True
                RadioButton12.Checked = False
            End If

        End If


    End Sub




    Private Sub TabControl1_Selecting(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TabControlCancelEventArgs) Handles TabControl1.Selecting
        Dim str As String = Nothing
        If e.TabPage.Enabled = False Then
            e.Cancel = True
            MsgBox("Coming Soon!")
        End If

        If updating = 1 Then
            e.Cancel = True
        End If
        If e.TabPage.Name = "TabPage3" And SerialPort1.IsOpen Then
            Panel2.Enabled = True
            PropSerial.SerialLineOut("M3")  'Diagnostic Mode
        End If
        If e.TabPage.Name = "TabPage14" And SerialPort1.IsOpen Then
            'Label32.Text = PropSerial.GetRemote(999)


        End If


        If e.TabPage.Name = "TabPage7" And SerialPort1.IsOpen Then
            PropSerial.SerialLineOut("M1") ' Serial Monitor Mode
            AddHandler SerialPort1.DataReceived, AddressOf SerialPort1_busmon
        End If

        If e.TabPage.Name = "TabPage8" And SerialPort1.IsOpen Then
            resetDTR()
            AddHandler SerialPort1.DataReceived, AddressOf SerialPort1_portdisplay
        End If
    End Sub



#Region "Radio, Checkbox, Combobox Handler and loaders"
    Private Sub RadiobuttonLoad(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim sentby As RadioButton = sender
        RemoveHandler sentby.CheckedChanged, AddressOf radiobuttonupdate
        sentby.Checked = PropSerial.GetRemote(sender)
        AddHandler sentby.CheckedChanged, AddressOf radiobuttonupdate

    End Sub

    Private Sub radiobuttonupdate(ByVal sender As System.Object, ByVal e As System.EventArgs)
        PropSerial.setremote(sender)
    End Sub

    Private Sub comboboxload(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim sentby As ComboBox = CType(sender, ComboBox)
        RemoveHandler sentby.SelectedIndexChanged, AddressOf comboboxupdate
        Dim sindex As Integer = PropSerial.GetRemote(sender)


        Try

            sentby.SelectedIndex = sindex
        Catch ex As Exception
            sentby.SelectedIndex = -1
        End Try
        AddHandler sentby.SelectedIndexChanged, AddressOf comboboxupdate
    End Sub

    Private Sub comboboxupdate(ByVal sender As System.Object, ByVal e As System.EventArgs)
        PropSerial.setremote(sender)
    End Sub


    Private Sub checkboxload(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim sentby As CheckBox = sender
        RemoveHandler sentby.CheckedChanged, AddressOf checkboxupdate
        sentby.Checked = PropSerial.GetRemote(sender)
        AddHandler sentby.CheckedChanged, AddressOf checkboxupdate

    End Sub

    Private Sub checkboxupdate(ByVal sender As System.Object, ByVal e As System.EventArgs)
        PropSerial.setremote(sender)
    End Sub

#End Region
#Region "Serial Bus Monitor"
    Private Sub SerialPort1_busmon(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs)
        If SerialPort1.IsOpen Then
            Dim command As String = PropSerial.SerialLineIn()
            Dim sentby As String = PropSerial.SerialLineIn()
            Dim Dest As String = PropSerial.SerialLineIn()
            Dim time As DateTime = DateTime.Now
            Dim datestring As String = time.ToString("HH:mm:ss")
            ReceivedText(0, command, sentby, Dest, datestring)
        End If
    End Sub

    Private Sub SerialPort1_portdisplay(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs)
        If SerialPort1.IsOpen Then
            Dim command As String = SerialPort1.ReadExisting.Replace(vbCr, vbNewLine)
            AppendSerialMon(command)
        End If
    End Sub

    Private Sub AppendSerialMon(ByVal str As String)
        If Me.TextBox4.InvokeRequired Then
            Dim x As New SetSerialCallback(AddressOf AppendSerialMon)
            Me.Invoke(x, New Object() {str})
        Else

            Dim ctrlchar As Integer

            ctrlchar = str.IndexOf(newscreen)
            If ctrlchar > -1 Then
                str = str.Remove(ctrlchar, 1)
                TextBox4.Clear()
            End If



            TextBox4.AppendText(str)




        End If

    End Sub

    Private Sub ReceivedText(ByVal rowind As Integer, ByVal [text] As String, ByVal [text2] As String, ByVal [text3] As String, ByVal [text4] As String)

        If Me.DataGridView1.InvokeRequired Then
            Dim x As New SetTextCallback(AddressOf ReceivedText)
            Me.Invoke(x, New Object() {rowind, [text], [text2], [text3], [text4]})
        Else
            DataGridView1.Rows.Insert(rowind, [text], [text2], [text3], [text4])
        End If
    End Sub


    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        PropSerial.SerialLineOut("sersend")
        Dim str As String = TextBox2.Text
        Dim words As String() = str.Split(New Char() {" "c, ","c, "."c, "-"c, "_"c})
        For Each word In words
            If word <> "" Then
                PropSerial.SerialLineOut("N")
                PropSerial.SerialLineOut(word)
            End If
        Next
        PropSerial.SerialLineOut("serdone")

    End Sub
#End Region

    Private Sub TextBox2_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox2.KeyDown
        If (e.KeyCode = Keys.Return) Then
            If TextBox2.Text <> "" Then
                Button1_Click(sender, New System.EventArgs())
            End If
        End If

    End Sub

    Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
        If TextBox2.Text = "" Then
            Button1.Enabled = False
        Else
            Button1.Enabled = True
        End If

    End Sub

    Private Sub Button9_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button9.Click
        resetDTR()
    End Sub

    Private Sub TextBox5_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox5.KeyDown

        If (e.KeyCode = Keys.Return) Then
            TextBox5.Clear()
        End If
    End Sub

    Private Sub TextBox5_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox5.KeyPress
        SerialPort1.Write(Convert.ToChar(e.KeyChar))
    End Sub



#Region "Diagnostics Screens"


    'Private Sub rundiagrequest()
    '    'First thing that runs when the Run button is clicked.  It sets the Diagnostic Mode on
    '    'Runs LDDiagscreen with the selected fields
    '    'Runs Refreshdiagscreen (which populates the values
    '    'And if Refresh is TRUE, triggers a background worker to refresh regularly

    '    backgroundWorker2.WorkerSupportsCancellation = True
    '    ComboBox46.AccessibleName = Nothing
    '    backgroundWorker2.CancelAsync()

    '    PropSerial.SerialLineOut("Ms" & Convert.ToString(ComboBox45.SelectedItem.value))
    '    lddiagscreen(ComboBox45.SelectedItem.value, ComboBox46.SelectedItem.value)
    '    refreshdiagscreen()
    '    If ComboBox46.AccessibleName = "true" Then
    '        If Not Me.backgroundWorker2.IsBusy Then
    '            Me.backgroundWorker2.RunWorkerAsync()
    '        End If

    '    End If

    'End Sub
    Private Sub diagnosticbgrefresh(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles diagnosticBG.DoWork
        Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)



        Dim currlbl As formattedlabels
        Dim ctl As Control
        Dim listlen As Integer = MyControlArray.listlen - 1
        Dim curritem As Integer = 0
        'Dim currmbitem As ctrltoupdate

        While (curritem < listlen)
            If worker.CancellationPending Then
                Return
            End If

            ctl = MyControlArray(curritem)
            If ctl.GetType.Name = "formattedlabels" Then
                currlbl = ctl
                'If currlbl.query IsNot Nothing Then
                '    currmbitem = New ctrltoupdate
                '    currmbitem.ctrlid = curritem
                '    currmbitem.ctrlval = DiagnosticVal(DgValue, currlbl.query)
                '    CtrlMB.Add(currmbitem)
                'End If
            End If
            curritem = curritem + 1
        End While


    End Sub


    Private Sub rundiagrequest()
        'First thing that runs when the Run button is clicked.  It sets the Diagnostic Mode on
        'Runs LDDiagscreen with the selected fields
        'Runs Refreshdiagscreen (which populates the values
        'And if Refresh is TRUE, triggers a background worker to refresh regularly

        diagnosticBG.WorkerSupportsCancellation = True
        ComboBox46.AccessibleName = Nothing
        diagnosticBG.CancelAsync()

        lddiagscreen(ComboBox45.SelectedItem.value, ComboBox46.SelectedItem.value)

        PropSerial.SerialLineOut("Ms" & Convert.ToString(ComboBox45.SelectedItem.value))

        If ComboBox46.AccessibleName = "true" Then
            Me.diagnosticBG.RunWorkerAsync()
        End If

    End Sub

    Public Sub setposition(t As Object, cststyle As String, wid As Integer, heig As Integer)
        If cststyle <> Nothing Then
            t.complexstyle = cststyle
        End If

        If wid <> Nothing Then
            t.width = wid
        End If

        If heig <> Nothing Then
            t.height = heig
        End If

    End Sub

    'Public Sub lddiagscreen(ByVal ecuid As Integer, ByVal screenid As Integer)
    '    'Populates the Result with the corect labels.  

    '    Dim tlbl As formattedlabels
    '    Dim tbutton As New Button

    '    Dim tText As String


    '    Dim tpoint As New Point
    '    Dim tpoint2 As New Point

    '    Dim progmin, progmax As Integer
    '    Dim progshift As Integer
    '    Dim setrefresh As Boolean = False
    '    'Dim strversion = xmldoc.<config>.<stringlist>.@version

    '    Dim dropsquery = From dropitem In xmldoc.<config>.<resultscreens>.<screen> Where ((dropitem.@id = screenid) And (dropitem.@ecu = ecuid))
    '    If dropsquery.@refresh IsNot Nothing Then
    '        setrefresh = True
    '    End If
    '    ComboBox46.AccessibleName = Nothing
    '    MyControlArray.removeall()

    '    For Each subdrop In dropsquery.<dataval>
    '        'Check to see if a custom position has been set for the label or display in XML
    '        If (subdrop.<label>.@xpos <> Nothing) And (subdrop.<label>.@ypos <> Nothing) Then
    '            tpoint.Y = subdrop.<label>.@ypos
    '            tpoint.X = subdrop.<label>.@xpos
    '        Else
    '            tpoint = Nothing
    '        End If

    '        If subdrop.<tooltip>.Value <> Nothing Then
    '            tText = subdrop.<tooltip>.Value
    '        Else
    '            tText = subdrop.<label>.Value
    '        End If

    '        If (subdrop.<query>.@xpos <> Nothing) And (subdrop.<query>.@ypos <> Nothing) Then
    '            tpoint2.Y = subdrop.<query>.@ypos
    '            tpoint2.X = subdrop.<query>.@xpos
    '        Else
    '            tpoint2 = Nothing
    '        End If

    '        Select Case subdrop.@type
    '            Case "range"
    '                'First, The range label, which is flagged for refresh
    '                Dim xlbl As formattedlabels = MyControlArray.AddNewlabel("r", subdrop.<label>.@width, subdrop.<label>.Value, tpoint, subdrop.<label>.@column)
    '                xlbl.query = subdrop.<query>.Value
    '                xlbl.querytype = subdrop.@type

    '                xlbl.AccessibleDescription = subdrop.<query>.Value
    '                xlbl.AccessibleName = DgValRange
    '                xlbl.complexstyle = subdrop.<label>.@complexstyle
    '                ToolTip1.SetToolTip(xlbl, tText)
    '                'Then, the progress bar
    '                Dim xdisplay As ProgressBar = MyControlArray.AddNewProgress(tpoint2, subdrop.<query>.@column)
    '                xdisplay.Height = xlbl.Height - 4
    '                'Set the Progress bar's min and Max
    '                progmin = DiagnosticVal(DgMin, subdrop.<query>.Value)
    '                progmax = DiagnosticVal(DgMax, subdrop.<query>.Value)
    '                ToolTip1.SetToolTip(xdisplay, "Range: " & CStr(progmin) & " - " & CStr(progmax))


    '                'Convert if the values are negative
    '                If progmin < 0 Then
    '                    progshift = Math.Abs(progmin)
    '                    progmin = progmin + progshift
    '                    progmax = progmax + progshift
    '                    xdisplay.AccessibleName = Convert.ToString(progshift)
    '                End If
    '                xdisplay.Maximum = progmax
    '                xdisplay.Minimum = progmin
    '                'Finally, set the unit for the range
    '                MyControlArray.AddNewlabel("r", 43, "value", Nothing, subdrop.<query>.@column)
    '                tlbl = MyControlArray.AddNewlabel("l", 43, DiagnosticUnit(DgUnit & subdrop.<query>.Value), Nothing, subdrop.<query>.@column)
    '                tlbl.TextAlign = ContentAlignment.MiddleLeft
    '                If tpoint = Nothing Then
    '                    MyControlArray.nextrow(subdrop.<label>.@column)
    '                End If

    '            Case "label", "binary"
    '                Dim xlbl As formattedlabels = MyControlArray.AddNewlabel(Nothing, subdrop.<label>.@width, subdrop.<label>.Value, tpoint, subdrop.<label>.@column)
    '                xlbl.query = subdrop.<query>.Value
    '                xlbl.querytype = subdrop.@type
    '                xlbl.AccessibleDescription = subdrop.<query>.Value
    '                xlbl.AccessibleName = subdrop.@type
    '                tlbl = MyControlArray.AddNewlabel(Nothing, subdrop.<query>.@width, "val", tpoint2, subdrop.<query>.@column)
    '                If tpoint = Nothing Then
    '                    MyControlArray.nextrow(subdrop.<label>.@column)
    '                End If
    '                ToolTip1.SetToolTip(xlbl, tText)

    '            Case "button"
    '                tbutton = MyControlArray.AddNewButton(subdrop.<label>.Value, subdrop.<query>.Value, tpoint, subdrop.<label>.@column)
    '                ToolTip1.SetToolTip(tbutton, subdrop.<tooltip>.Value)
    '                If tpoint = Nothing Then
    '                    MyControlArray.nextrow(subdrop.<label>.@column)
    '                End If
    '                ToolTip1.SetToolTip(tbutton, tText)
    '        End Select

    '    Next

    '    If setrefresh = True Then
    '        ComboBox46.AccessibleName = "true"
    '    End If

    'End Sub

    Public Const DgErrCt As String = "E"
    Public Const DgValRange As String = "range"
    Public Const DgLabel As String = "label"
    Public Const Dgbinary As String = "binary"
    Public Const DgValue As String = "vv"
    Public Const DgUnit As String = "vu"
    Public Const DgMin As String = "vm"
    Public Const DgMax As String = "vM"


    Public Function refreshdiagscreen()
        'After labels are loaded, Refresh does the initial refresh and handles any additional refreshes

        Dim currlbl, progbar As formattedlabels
        Dim ctl As Control
        Dim sent As String
        Dim listlen As Integer = MyControlArray.listlen - 1
        Dim curritem As Integer = 1



        While (curritem < listlen)
            ctl = MyControlArray(curritem)
            If ctl.GetType.Name = "formattedlabels" Then
                currlbl = ctl
                'If currlbl.query IsNot Nothing Then
                '    currlbl.queryvalue = DiagnosticVal(DgValue, currlbl.query)
            End If

            curritem = curritem + 1
        End While


        Return 0
    End Function

    Public Sub lddiagscreen(ByVal ecuid As Integer, ByVal screenid As Integer)
        'Populates the Result with the corect labels.  

        Dim tlbl As formattedlabels
        Dim tbutton As New Button

        Dim tooltipText As String
        Dim QueryText As String


        Dim tpoint As New Point
        Dim tpoint2 As New Point

        Dim progmin, progmax As Integer
        Dim progshift As Integer
        Dim setrefresh As Boolean = False

        Dim dropsquery = From dropitem In xmldoc.<config>.<resultscreens>.<screen> Where ((dropitem.@id = screenid) And (dropitem.@ecu = ecuid))
        If dropsquery.@refresh IsNot Nothing Then
            setrefresh = True
        End If
        ComboBox46.AccessibleName = Nothing
        MyControlArray.removeall()

        For Each subdrop In dropsquery.<dataval>
            tpoint = Nothing
            tpoint2 = Nothing
            tooltipText = subdrop.<label>.Value
            QueryText = subdrop.<query>.Value


            'Check to see if a custom position has been set for the label or display in XML
            If (subdrop.<label>.@xpos <> Nothing) And (subdrop.<label>.@ypos <> Nothing) Then
                tpoint.Y = subdrop.<label>.@ypos
                tpoint.X = subdrop.<label>.@xpos
            End If

            If subdrop.<tooltip>.Value <> Nothing Then
                tooltipText = subdrop.<tooltip>.Value
            End If

            If (subdrop.<query>.@xpos <> Nothing) And (subdrop.<query>.@ypos <> Nothing) Then
                tpoint2.Y = subdrop.<query>.@ypos
                tpoint2.X = subdrop.<query>.@xpos
            End If


            Select Case subdrop.@type
                Case "range"
                    Dim xlbl2 As New DiagnosticControl
                    ToolTip1.SetToolTip(xlbl2, tooltipText)
                    xlbl2.ControlLabel = subdrop.<label>.Value
                    xlbl2.ControlUnit = DiagnosticUnit(DgUnit & subdrop.<query>.Value)
                    xlbl2.RangeMin = DiagnosticUnit(DgMin & QueryText)
                    xlbl2.RangeMax = DiagnosticUnit(DgMax & QueryText)
                    xlbl2.DrawProgressbar = True
                    xlbl2.SetValue = DiagnosticVal(DgValue, QueryText)



                    'First, The range label, which is flagged for refresh
                    Dim xlbl As formattedlabels = MyControlArray.AddNewlabel("r", subdrop.<label>.@width, subdrop.<label>.Value, tpoint, subdrop.<label>.@column)
                    'xlbl.query = subdrop.<query>.Value
                    'xlbl.querytype = subdrop.@type
                    'xlbl.complexstyle = subdrop.<label>.@complexstyle

                    'Then, the progress bar
                    'xdisplay.Height = xlbl.Height - 4
                    'Finally, set the unit for the range
                    xlbl.addlabeltxt("r", 43, Nothing, subdrop.<query>.@column)
                    tlbl = MyControlArray.AddNewlabel("l", 43, DiagnosticUnit(DgUnit & subdrop.<query>.Value), Nothing, subdrop.<query>.@column)
                    tlbl.TextAlign = ContentAlignment.MiddleLeft
                    If tpoint = Nothing Then
                        MyControlArray.nextrow(subdrop.<label>.@column)
                    End If

                Case "label", "binary"
                    Dim xlbl As formattedlabels = MyControlArray.AddNewlabel(Nothing, subdrop.<label>.@width, subdrop.<label>.Value, tpoint, subdrop.<label>.@column)
                    'xlbl.query = subdrop.<query>.Value
                    'xlbl.querytype = subdrop.@type
                    xlbl.AccessibleDescription = subdrop.<query>.Value
                    xlbl.AccessibleName = subdrop.@type
                    tlbl = MyControlArray.AddNewlabel(Nothing, subdrop.<query>.@width, "val", tpoint2, subdrop.<query>.@column)
                    If tpoint = Nothing Then
                        MyControlArray.nextrow(subdrop.<label>.@column)
                    End If
                    'ToolTip1.SetToolTip(xlbl, XText)

                Case "button"
                    tbutton = MyControlArray.AddNewButton(subdrop.<label>.Value, subdrop.<query>.Value, tpoint, subdrop.<label>.@column)
                    ToolTip1.SetToolTip(tbutton, subdrop.<tooltip>.Value)
                    If tpoint = Nothing Then
                        MyControlArray.nextrow(subdrop.<label>.@column)
                    End If
                    'ToolTip1.SetToolTip(tbutton, tText)
            End Select

        Next

        If setrefresh = True Then
            ComboBox46.AccessibleName = "true"
        End If

    End Sub



    'Public Function refreshdiagscreen()
    '    'After labels are loaded, Refresh does the initial refresh and handles any additional refreshes


    '    Dim listlen As Integer = MyControlArray.listlen - 1
    '    Dim curritem As Integer = 0
    '    Dim currval As String
    '    Dim shiftstr As String
    '    Dim progshift As Integer
    '    Dim ISErrorScreen As Boolean = False
    '    Dim errorcount As Integer

    '    While (curritem < listlen)
    '        If MyControlArray(curritem).AccessibleDescription IsNot Nothing Then
    '            currval = DiagnosticVal(DgValue, MyControlArray(curritem).AccessibleDescription)


    '            If MyControlArray(curritem).AccessibleDescription = DgErrCt Then
    '                Dim x As formattedlabels = MyControlArray(curritem)
    '                Dim y As formattedlabels = MyControlArray(curritem + 1)
    '                'x.complexstyle = "ErrorLBL"
    '                'y.complexstyle = "ErrorCT"
    '                ISErrorScreen = True
    '                errorcount = currval
    '            End If


    '            If MyControlArray(curritem).AccessibleName = DgValRange Then
    '                Dim progbar As ProgressBar = MyControlArray(curritem + 1)
    '                MyControlArray(curritem + 2).Text = currval
    '                If progbar.AccessibleName IsNot Nothing Then
    '                    shiftstr = progbar.AccessibleName
    '                    progshift = Convert.ToInt32(shiftstr)
    '                    currval = currval + progshift
    '                End If
    '                progbar.Value = currval

    '            End If

    '            If MyControlArray(curritem).AccessibleName = Dgbinary Then
    '                Dim txtlabel As Label = MyControlArray(curritem + 1)
    '                txtlabel.Text = currval
    '                If currval = 0 Then
    '                    txtlabel.Text = "Off"
    '                End If
    '                If currval = 1 Then
    '                    txtlabel.Text = "On"
    '                End If
    '            End If


    '            If MyControlArray(curritem).AccessibleName = DgLabel Then
    '                Dim txtlabel As Label = MyControlArray(curritem + 1)
    '                txtlabel.Text = currval
    '            End If
    '        End If
    '        curritem = curritem + 1
    '    End While

    '    If (ISErrorScreen = True) And (errorcount > 0) Then
    '        loaderrors(errorcount)
    '    End If

    '    Return 0
    'End Function

    Public Function loaderrors(ByVal errorcount)
        'Dim doc = XDocument.Load(New StreamReader([Assembly].GetEntryAssembly.GetManifestResourceStream(XMLfile)))
        Dim tlbl As Label
        Dim tbtn As Button
        Dim i As Integer = 1
        Dim x As Char
        Dim errorid As Integer
        Dim errordesc As String
        Dim selecu As Integer = ComboBox45.SelectedItem.value

        If (ComboBox45.SelectedItem.value = 34) Or (ComboBox45.SelectedItem.value = 36) Then
            'Add Header
            selecu = 34
            'MyControlArray.AddNewlabel("r", 30, "ID")
            'MyControlArray.AddNewlabel("r", 150, "Description")
            'MyControlArray.AddNewlabel("r", 60, "Frequency")
            'MyControlArray.AddNewlabel("r", 60, "Last Occured")
            'MyControlArray.AddNewlabel("r", 60, "Eng RPM")
            'MyControlArray.AddNewlabel("r", 60, "Eng Load")
            'MyControlArray.AddNewlabel("r", 60, "Eng Temp")
            'MyControlArray.AddNewlabel("r", 60, "Voltage")
            'MyControlArray.AddNewlabel("r", 150, "Other Error Notes")
            'MyControlArray.nextline()

            Do While i <= errorcount
                x = Convert.ToString(i)
                DiagnosticVal("e", x)
                errorid = DiagnosticVal("E", "#")

                tlbl = MyControlArray.AddNewlabel(Nothing, 60, errorid, Nothing, 1)
                tlbl.TextAlign = ContentAlignment.MiddleRight
                errordesc = "N/A"

                Dim drop3 = From dropitem3 In xmldoc.<config>.<errorlist>.<error> Where ((dropitem3.@id = errorid) And (dropitem3.@ecu = selecu))
                If drop3.Value IsNot Nothing Then
                    errordesc = drop3.Value
                End If

                'Error Title'
                tlbl = MyControlArray.AddNewlabel("head", 600, errordesc, Nothing, 1)
                tlbl.TextAlign = ContentAlignment.MiddleLeft
                MyControlArray.nextrow(1)



                tlbl = MyControlArray.AddNewlabel(Nothing, 60, DiagnosticVal("E", "f"), Nothing, 1)
                tlbl.TextAlign = ContentAlignment.MiddleRight

                tlbl = MyControlArray.AddNewlabel(Nothing, 60, DiagnosticVal("E", "h"), Nothing, 1)
                tlbl.TextAlign = ContentAlignment.MiddleRight

                tlbl = MyControlArray.AddNewlabel(Nothing, 60, DiagnosticVal("E", "r"), Nothing, 1)
                tlbl.TextAlign = ContentAlignment.MiddleRight

                tlbl = MyControlArray.AddNewlabel(Nothing, 60, DiagnosticVal("E", "L"), Nothing, 1)
                tlbl.TextAlign = ContentAlignment.MiddleRight

                tlbl = MyControlArray.AddNewlabel(Nothing, 60, DiagnosticVal("E", "t"), Nothing, 1)
                tlbl.TextAlign = ContentAlignment.MiddleRight

                tlbl = MyControlArray.AddNewlabel(Nothing, 60, DiagnosticVal("E", "b"), Nothing, 1)
                tlbl.TextAlign = ContentAlignment.MiddleRight

                tlbl = MyControlArray.AddNewlabel(Nothing, 150, "Other Error Notes", Nothing, 1)
                tlbl.TextAlign = ContentAlignment.MiddleRight

                MyControlArray.nextrow(1)
                i = i + 1
            Loop

            MyControlArray.nextrow(1)

            tbtn = MyControlArray.AddNewButton("Clear", "c", Nothing, 1)




        End If
        Return 0
    End Function

    Public Function DiagnosticVal(ByVal requesttype As String, ByVal ECUvalue As String) As Decimal
        Dim str As String = Nothing
        str = requesttype
        str = str & Convert.ToString(ECUvalue)
        PropSerial.SerialLineOut(str)
        str = PropSerial.SerialLineIn()

        Return Convert.ToDecimal(str)
    End Function

    Public Function DiagnosticUnit(ByVal ECUvalue As String) As String
        Dim str As String = Nothing
        str = DgUnit & Convert.ToString(ECUvalue)
        PropSerial.SerialLineOut(str)
        str = PropSerial.SerialLineIn()
        Return str
    End Function

    Private Sub ComboBox45_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox45.SelectedIndexChanged
        Dim newcmdlist As Integer = ComboBox45.SelectedItem.value

        Dim dropsquery = From dropitem In xmldoc.<config>.<resultscreens>.<activitylists>.<list> Where dropitem.@id = newcmdlist
        Button8.Enabled = False
        ComboBox46.Items.Clear()
        ComboBox46.Text = "Diagnostic Task..."

        For Each subdrop In dropsquery.<selectable>
            ComboBox46.Items.Add(New clCombobox(subdrop.Value, subdrop.Attribute("value").Value))

        Next
        ComboBox46.Enabled = True
    End Sub

    'Private Sub backgroundWorker2_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles backgroundWorker2.DoWork
    '    Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
    '    Dim i As Integer = 0
    '    Do While i < 50
    '        If worker.CancellationPending Then

    '            e.Cancel = True
    '            Return
    '        End If
    '        Thread.Sleep(10)
    '        i = i + 1
    '    Loop
    'End Sub

    'Private Sub backgroundWorker2_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) _
    '        Handles backgroundWorker2.RunWorkerCompleted
    '    If ComboBox46.AccessibleName = "true" Then
    '        If TabControl1.SelectedTab.Name = "TabPage3" Then
    '            refreshdiagscreen()
    '            backgroundWorker2.CancelAsync()
    '            Me.backgroundWorker2.RunWorkerAsync()
    '        End If


    '    End If


    'End Sub

#End Region




#Region "Boot Mode Radiobutton flip-flops"
    'Private Sub RadioButton6_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton6.CheckedChanged
    '    If RadioButton6.Checked = True Then
    '        RadioButton12.Checked = True
    '        GroupBox10.Enabled = False
    '        GroupBox12.Enabled = False
    '        GroupBox30.Enabled = False
    '    End If

    '    If RadioButton6.Checked = False Then
    '        GroupBox10.Enabled = True
    '        GroupBox12.Enabled = True
    '        GroupBox30.Enabled = True
    '    End If


    'End Sub

    '    Private Sub RadioButton12_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton12.CheckedChanged
    '        If RadioButton12.Checked = True Then
    '            TabControl2.Enabled = True
    '            GroupBox20.Enabled = True
    '        End If

    '        If RadioButton12.Checked = False Then
    '            TabControl2.Enabled = False
    '            GroupBox20.Enabled = False
    '        End If

    '    End Sub

    '    Private Sub RadioButton13_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton13.CheckedChanged
    '        If RadioButton13.Checked = True Then
    '            TabControl2.Enabled = False
    '            GroupBox20.Enabled = False
    '        End If

    '        If RadioButton13.Checked = False Then
    '            TabControl2.Enabled = True
    '            GroupBox20.Enabled = True
    '        End If


    '    End Sub

    '    Private Sub RadioButton5_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton5.CheckedChanged
    '        If RadioButton5.Checked = True Then
    '            RadioButton13.Checked = True

    '            GroupBox10.Enabled = True
    '            GroupBox12.Enabled = True
    '            GroupBox30.Enabled = True
    '        End If

    '        If RadioButton5.Checked = False Then
    '            GroupBox10.Enabled = False
    '            GroupBox12.Enabled = False
    '            GroupBox30.Enabled = False
    '        End If

    '    End Sub
#End Region
#Region "Button Nav handlers"
    Private Sub ComboBox46_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox46.SelectedIndexChanged
        Button8.Enabled = True
    End Sub

    Private Sub ToTab2(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LinkLabel8.LinkClicked
        TabControl1.SelectedTab = TabPage2
    End Sub


    Private Sub ToTab3(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button10.Click
        TabControl1.SelectedTab = TabPage3
    End Sub

    Private Sub ToTab6(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
        TabControl1.SelectedTab = TabPage6
    End Sub

    Private Sub ToTab4(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LinkLabel1.LinkClicked
        TabControl1.SelectedTab = TabPage4
    End Sub

    Private Sub ToTab8(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LinkLabel2.LinkClicked
        TabControl1.SelectedTab = TabPage8
    End Sub


    Private Sub ToTab7(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LinkLabel3.LinkClicked
        TabControl1.SelectedTab = TabPage7
    End Sub

    Private Sub ToTab1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button11.Click, Button13.Click, Button15.Click, Button16.Click, Button17.Click, Button18.Click, Button19.Click, Button25.Click
        TabControl1.SelectedTab = TabPage1
    End Sub

    Private Sub ToTab9(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button14.Click, Button5.Click
        TabControl1.SelectedTab = TabPage9
    End Sub

    Private Sub ToTab14(sender As Object, e As EventArgs)
        TabControl1.SelectedTab = TabPage14

    End Sub


    Private Sub LinkLabel6_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel6.LinkClicked
        Dim secondform As New Diagnostics
        secondform.panelsize = "step1"
        secondform.Show()
    End Sub

    Private Sub Button12_Click_2(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button12.Click
        PropSerial.SerialLineOut("M0")
        PropSerial.SerialLineOut(ComboBox1.SelectedIndex)

    End Sub
#End Region


    Private Sub LinkLabel11_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs)


        'If Formattedlabels1.HelpBox IsNot Nothing Then
        '    Formattedlabels1.HelpBox.Close()
        'End If



        '        If My.Application.OpenForms.Cast(Of Form)().Contains(Form2) Then
        ' MsgBox("open")
        ' End If


        'Dim secondform As New Diagnostics
        'secondform.panelsize = "step1"
        'secondform.Show()





        'Dim subdropquery = From duplist In xmldoc.<config>.<selectionlists>.<list> Where _
        '           duplist.@name = linkedlistname
        'ob.text = subdropquery.<label>.Value

        '        <helpdetail>
        '  <item id="S19">
        '    <title>Disa Valve Active Status</title>
        '    <unit>On/Off</unit>
        '    <detail>Reads ON when the ECM is commanding the solenoid to energize, closing the change-over valve, and reads OFF when the ECM de-energizes the solenoid to open the change-over valve.  The change-over valve controls what path the intake air charge takes to reach the intake manifold. Below 4,840 RPM, the ECM commands the valve closed. This routes the intake air charge through the long intake pipe, resulting in increased engine torque. Above 4,840 RPM, the ECM commands the valve open. This routes the intake air through the short pipe, resulting in additional power output.</detail>
        '  </item>
        '</helpdetail>

    End Sub

    Private Sub LinkLabel4_LinkClicked_1(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel4.LinkClicked, LinkLabel7.LinkClicked
        Dim secondform As New BootModes
        secondform.Show()
    End Sub


    Private Sub Chart1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub Button20_Click(sender As Object, e As EventArgs) Handles Button20.Click
        Me.diagnosticBG.RunWorkerAsync()
    End Sub







    Private Sub TabControl1_DrawItem(sender As Object, e As DrawItemEventArgs)
        Dim tgtframe As TabControl = CType(sender, TabControl)

        Dim tgttab As TabPage = tgtframe.SelectedTab
        'tgttab.BackColor = Color.White



    End Sub

    'Sub startthread()
    '    Dim ob As New diagnosticrefresher
    '    ob.Host = Panel2
    '    ''AddHandler WC.FinishedCounting, AddressOf _FinishedCountingEventHandler
    '    DiagThread = New System.Threading.Thread(AddressOf ob.refreshdiagnostics)
    '    '' Start the new thread.
    '    DiagThread.Start()

    'End Sub




    Private Sub Button22_Click(sender As Object, e As EventArgs)

    End Sub



    Private Sub Button23_Click(sender As Object, e As EventArgs) Handles Button23.Click
        PropSerial.SerialLineOut("G" & ComboBox9.SelectedItem.value & TextBox8.Text)
        TextBox10.Text = PropSerial.SerialLineIn()
    End Sub

    Private Sub Button24_Click(sender As Object, e As EventArgs) Handles Button24.Click
        PropSerial.SerialLineOut("S" & ComboBox9.SelectedItem.value & TextBox8.Text)
        PropSerial.SerialLineOut(TextBox10.Text)


    End Sub

    Private Sub LinkLabel13_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel13.LinkClicked
        PropSerial.SerialLineOut("M5")

    End Sub




    Private Sub LinkLabel12_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel12.LinkClicked
        PropSerial.setdebugstrings()
    End Sub


    Private Sub TextBox6_TextChanged(sender As Object, e As EventArgs) Handles TextBox6.TextChanged

    End Sub

    Private Sub GroupBox14_Enter(sender As Object, e As EventArgs) Handles GroupBox14.Enter

    End Sub

    Private Sub FlowLayoutPanel1_ControlAdded(sender As Object, e As ControlEventArgs)

    End Sub

    Private Sub FlowLayoutPanel1_Paint(sender As Object, e As PaintEventArgs)

    End Sub

    Private Sub Button22_Click_1(sender As Object, e As EventArgs) Handles Button22.Click
        'ImprovedFlowpanel1.rwControlCollection.Add(New DiagnosticControl With {.BorderStyle = BorderStyle.FixedSingle, .Width = 115, .Height = 30, .RangeMin = 0, .RangeMax = 100, .SetValue = 5})
        'ImprovedFlowpanel1.controls.Add(New DiagnosticControl With {.BorderStyle = BorderStyle.FixedSingle, .Width = 115, .Height = 30, .RangeMin = 0, .RangeMax = 100, .SetValue = 5})
        loadctrls(30, 34)

    End Sub

    Private Sub Button26_Click(sender As Object, e As EventArgs) Handles Button26.Click
        ImprovedFlowpanel1.Controls.Clear()

    End Sub

    Sub loadctrls(screenID As Integer, ecuid As Integer)
        Dim newscreenctrls As New List(Of Control)
        Dim tctrl As New DiagnosticControl

        Dim dropsquery = From dropitem In xmldoc.<config>.<resultscreens>.<screen> Where ((dropitem.@id = screenID) And (dropitem.@ecu = ecuid))


        dropsquery.<dataval>.ToList.ForEach(Sub(x)
                                                Dim progset As Boolean = False
                                                If x.@type = "range" Then
                                                    progset = True
                                                End If
                                                If x.@type = "range" Or x.@type = "label" Then
                                                    tctrl = New DiagnosticControl With {.RangeMin = 1, .RangeMax = 100, .ControlLabel = x.<label>.Value, .BorderStyle = BorderStyle.FixedSingle, .Width = 150, .Height = 30}
                                                    tctrl.SetValue = 5
                                                    tctrl.DrawProgressbar = progset
                                                    newscreenctrls.Add(tctrl)



                                                End If
                                            End Sub)

        If newscreenctrls.Count > 0 Then
            ImprovedFlowpanel1.addctrlblock(newscreenctrls)
        End If


    End Sub


    'ImprovedFlowpanel1.controls.Add(New DiagnosticControl With {.BorderStyle = BorderStyle.FixedSingle, .Width = 115, .Height = 30, .RangeMin = 0, .RangeMax = 100, .SetValue = 5})

    'foreach(Sub(p) p.Equals = 1)






    '    For Each subdrop In dropsquery.<dataval>
    '        'Check to see if a custom position has been set for the label or display in XML
    '        If (subdrop.<label>.@xpos <> Nothing) And (subdrop.<label>.@ypos <> Nothing) Then
    '            tpoint.Y = subdrop.<label>.@ypos
    '            tpoint.X = subdrop.<label>.@xpos
    '        Else
    '            tpoint = Nothing
    '        End If

    '        If subdrop.<tooltip>.Value <> Nothing Then
    '            tText = subdrop.<tooltip>.Value
    '        Else
    '            tText = subdrop.<label>.Value
    '        End If

    '        If (subdrop.<query>.@xpos <> Nothing) And (subdrop.<query>.@ypos <> Nothing) Then
    '            tpoint2.Y = subdrop.<query>.@ypos
    '            tpoint2.X = subdrop.<query>.@xpos
    '        Else
    '            tpoint2 = Nothing
    '        End If

    '        Select Case subdrop.@type
    '            Case "range"
    '                'First, The range label, which is flagged for refresh
    '                Dim xlbl As formattedlabels = MyControlArray.AddNewlabel("r", subdrop.<label>.@width, subdrop.<label>.Value, tpoint, subdrop.<label>.@column)
    '                xlbl.query = subdrop.<query>.Value
    '                xlbl.querytype = subdrop.@type

    '                xlbl.AccessibleDescription = subdrop.<query>.Value
    '                xlbl.AccessibleName = DgValRange
    '                xlbl.complexstyle = subdrop.<label>.@complexstyle
    '                ToolTip1.SetToolTip(xlbl, tText)
    '                'Then, the progress bar
    '                Dim xdisplay As ProgressBar = MyControlArray.AddNewProgress(tpoint2, subdrop.<query>.@column)
    '                xdisplay.Height = xlbl.Height - 4
    '                'Set the Progress bar's min and Max
    '                progmin = DiagnosticVal(DgMin, subdrop.<query>.Value)
    '                progmax = DiagnosticVal(DgMax, subdrop.<query>.Value)
    '                ToolTip1.SetToolTip(xdisplay, "Range: " & CStr(progmin) & " - " & CStr(progmax))


    '                'Convert if the values are negative
    '                If progmin < 0 Then
    '                    progshift = Math.Abs(progmin)
    '                    progmin = progmin + progshift
    '                    progmax = progmax + progshift
    '                    xdisplay.AccessibleName = Convert.ToString(progshift)
    '                End If
    '                xdisplay.Maximum = progmax
    '                xdisplay.Minimum = progmin
    '                'Finally, set the unit for the range
    '                MyControlArray.AddNewlabel("r", 43, "value", Nothing, subdrop.<query>.@column)
    '                tlbl = MyControlArray.AddNewlabel("l", 43, DiagnosticUnit(DgUnit & subdrop.<query>.Value), Nothing, subdrop.<query>.@column)
    '                tlbl.TextAlign = ContentAlignment.MiddleLeft
    '                If tpoint = Nothing Then
    '                    MyControlArray.nextrow(subdrop.<label>.@column)
    '                End If

    '            Case "label", "binary"
    '                Dim xlbl As formattedlabels = MyControlArray.AddNewlabel(Nothing, subdrop.<label>.@width, subdrop.<label>.Value, tpoint, subdrop.<label>.@column)
    '                xlbl.query = subdrop.<query>.Value
    '                xlbl.querytype = subdrop.@type
    '                xlbl.AccessibleDescription = subdrop.<query>.Value
    '                xlbl.AccessibleName = subdrop.@type
    '                tlbl = MyControlArray.AddNewlabel(Nothing, subdrop.<query>.@width, "val", tpoint2, subdrop.<query>.@column)
    '                If tpoint = Nothing Then
    '                    MyControlArray.nextrow(subdrop.<label>.@column)
    '                End If
    '                ToolTip1.SetToolTip(xlbl, tText)

    '            Case "button"
    '                tbutton = MyControlArray.AddNewButton(subdrop.<label>.Value, subdrop.<query>.Value, tpoint, subdrop.<label>.@column)
    '                ToolTip1.SetToolTip(tbutton, subdrop.<tooltip>.Value)
    '                If tpoint = Nothing Then
    '                    MyControlArray.nextrow(subdrop.<label>.@column)
    '                End If
    '                ToolTip1.SetToolTip(tbutton, tText)
    '        End Select

    '    Next

    '    If setrefresh = True Then
    '        ComboBox46.AccessibleName = "true"
    '    End If























    Private Sub CheckBox40_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox40.CheckedChanged




        'Dim sent As Control = CType(sender, Control)
        'PropSerial.GetRemote(sender)
    End Sub

    Private Sub Button27_Click(sender As Object, e As EventArgs) Handles Button27.Click
        PropSerial.HousekeepingCtrls(PropIO.HousekeepingFunctions.LightSwitch)
        Debug.WriteLine("Housekeeping Done")

    End Sub
End Class

'Public Class diagnosticrefresher
'    Private HostForm As System.Windows.Forms.Panel

'    Public Property Host() As System.Windows.Forms.Panel
'        Get
'            Return Me.HostForm
'        End Get
'        Set(ByVal value As System.Windows.Forms.Panel)
'            HostForm = value
'        End Set
'    End Property


'    Sub refreshdiagnostics()
'        Dim tlbl As New Label
'        tlbl.Name = "testbtn"
'        tlbl.TextAlign = ContentAlignment.MiddleRight
'        tlbl.Size = New System.Drawing.Size(64, 32)
'        tlbl.BorderStyle = 1
'        tlbl.Location = New Point(20, 25)
'        tlbl.Text = "hey"
'        tlbl.Visible = True
'        Host.Controls.Add(tlbl)
'        MsgBox("hey thread")
'    End Sub




'End Class










Public Class formattedlabels
    Inherits Windows.Forms.Label
    Private _helpid As String
    Private _helpbox As Form2 = Nothing
    Private styleflag As String
    Private _query As String
    Private _querytype As String
    Private _queryvalue As Single
    Private _progressmin As Single
    Private _progressmax As Single
    Private _progressvalue As Single
    Public labelvalue As formattedlabels
#Region "Properties"

    ReadOnly Property HelpBox() As Form2
        Get
            Return CType(_helpbox, Form2)
        End Get
    End Property



    Property helpid() As String
        Get
            Return _helpid
        End Get
        Set(ByVal value As String)
            If value <> Nothing Then
                Dim helpitem = From helpquery In Form1.xmldoc.<config>.<helpdetail>.<item> Where helpquery.@id = value
                If helpitem.Value <> Nothing Then
                    AddHandler Me.Click, AddressOf linkclick
                    AddHandler Me.MouseHover, AddressOf linkhover
                    AddHandler Me.MouseLeave, AddressOf linkleave
                    _helpid = value
                End If
            End If

            If value = Nothing Then
                RemoveHandler Me.Click, AddressOf linkclick
                RemoveHandler Me.MouseHover, AddressOf linkhover
                RemoveHandler Me.MouseLeave, AddressOf linkleave
                _helpid = value
            End If

        End Set
    End Property
    Property complexstyle() As String
        Get
            Return Me.styleflag
        End Get
        Set(ByVal value As String)
            Select Case value
                Case "head"
                    Dim x As New System.Drawing.Font("Microsoft Sans Serif", 10)
                    Me.Font = x
                    Me.Height = 18
                Case "ErrorCT"
                    Me.TextAlign = ContentAlignment.TopLeft
                Case "ErrorLBL"
                    Me.TextAlign = ContentAlignment.TopRight
            End Select
            styleflag = value
        End Set
    End Property
#End Region

    Public Function addlabeltxt(algn, size, specialformat, col) As formattedlabels
        'labelvalue = Form1.MyControlArray.AddNewlabel(algn, size, queryvalue, specialformat, col)
        Return labelvalue


    End Function



    Public Sub linkclick(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim i As String

        'Dim xnew As XElement = Nothing
        'xnew.Value = "bold"
        Dim helpitem = From helpquery In Form1.xmldoc.<config>.<helpdetail>.<item> Where helpquery.@id = helpid
        For Each xe In helpitem.<detail>.Elements
            If xe.Name = "b" Then
                xe.Value = ControlChars.Lf
            End If
            If xe.Name = "p" Then
                xe.Value = ControlChars.Lf & ControlChars.Lf
            End If
        Next


        If HelpBox Is Nothing OrElse HelpBox.IsDisposed Then
            _helpbox = New Form2
            HelpBox.title = helpitem.<title>.Value
            HelpBox.unit = helpitem.<unit>.Value
            HelpBox.detail = helpitem.<detail>.Value
            'HelpBox.detail = helpitem.<detail>.Value.Replace("??", ControlChars.Lf)

            HelpBox.Show()
        End If
    End Sub

    Public Sub linkhover(ByVal sender As Object, e As EventArgs)
        Me.Cursor = System.Windows.Forms.Cursors.Help
    End Sub
    Public Sub linkleave(ByVal sender As Object, e As EventArgs)
        Me.Cursor = System.Windows.Forms.Cursors.Default
    End Sub

    Public Sub New()
        MyBase.New()
    End Sub

    Private Sub InitializeComponent()
        Me.Name = "FormattedLabel"
    End Sub

End Class




Public Class clCombobox
    Public cname As String
    Public cvalue As Object

    Public Property Display() As String
        Get
            Return Me.cname
        End Get
        Set(ByVal value As String)
            Me.cname = value
        End Set
    End Property
    Public Property Value() As String
        Get
            Return Me.cvalue
        End Get

        Set(ByVal value As String)
            Me.cvalue = value
        End Set
    End Property


    Public Sub New(ByVal name As String, ByVal value As String)
        cname = name
        cvalue = value
    End Sub

    Public Overrides Function ToString() As String
        Return cname
    End Function
End Class





Public Class ButtonArray
    Inherits System.Collections.CollectionBase
    Dim Columheight(680) As Integer
    Dim RowWidth(680) As Integer
    Dim rowMaxHeight(680) As Integer
    Dim rowElements As Integer
    Dim _itemvalue As Decimal
    Public rowControls As Integer
    Public currrowmax As Integer
    Private ReadOnly HostForm As System.Windows.Forms.Panel




    Default Public ReadOnly Property Item(ByVal Index As Integer) As System.Windows.Forms.Control
        Get
            Return CType(Me.List.Item(Index), System.Windows.Forms.Control)
        End Get
    End Property

    Public ReadOnly Property listlen As Integer
        Get
            Return Me.Count
        End Get
    End Property


    Public Sub New(ByVal host As System.Windows.Forms.Panel)
        HostForm = host
    End Sub
    Public Sub ClickHandler(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim str As String
        str = CType(CType(sender, System.Windows.Forms.Button).AccessibleName, String)
        Form1.DiagnosticVal("b", str)
    End Sub


    Public Sub nextrow(col As Integer)
        Dim x As Integer = Me.listlen - 1
        Dim i As Integer = x - rowControls + 1

        For z As Integer = x To i Step -1
            Me.List.Item(z).height = rowMaxHeight(col)
        Next
        Columheight(col) = rowMaxHeight(col) + Columheight(col)
        RowWidth(col) = 0
        rowControls = 0
        rowMaxHeight(col) = 0



    End Sub

    Public Function addControl(newcontrol As Windows.Forms.Control) As System.Windows.Forms.Control
        HostForm.Controls.Add(newcontrol)
        Return newcontrol


    End Function


    Public Function AddNewlabel(ByVal algn As String, ByVal wide As Integer, ByVal lbltext As String, pnt As Point, col As Integer) As System.Windows.Forms.Label

        Dim alabel As New formattedlabels()
        alabel.TextAlign = ContentAlignment.MiddleRight
        alabel.complexstyle = algn
        Me.List.Add(alabel)
        alabel.Width = wide
        alabel.BorderStyle = 1

        If pnt <> Nothing Then
            alabel.Location = pnt
        Else
            'Start the label at the end of the current column
            alabel.Top = Columheight(col) + 20
            alabel.Left = RowWidth(col) + col
            RowWidth(col) = RowWidth(col) + alabel.Width

            If alabel.Height > rowMaxHeight(col) Then
                rowMaxHeight(col) = alabel.Height
            End If
        End If

        alabel.Tag = Me.Count
        alabel.Text = lbltext


        HostForm.Controls.Add(alabel)
        rowControls = rowControls + 1
        Return alabel

    End Function

    Public Function AddNewProgress(pnt As Point, col As Integer) As System.Windows.Forms.ProgressBar
        Dim aprogress As New System.Windows.Forms.ProgressBar()
        Dim pad As New Padding(5, 0, 5, 0)
        aprogress.Style = ProgressBarStyle.Continuous
        aprogress.Height = 13
        aprogress.Width = 110
        aprogress.Margin = pad

        If pnt <> Nothing Then
            aprogress.Location = pnt
        Else
            'Start the label at the end of the current column
            aprogress.Top = Columheight(col) + 20
            aprogress.Left = RowWidth(col) + col
            RowWidth(col) = RowWidth(col) + aprogress.Width

            If aprogress.Height > rowMaxHeight(col) Then
                rowMaxHeight(col) = aprogress.Height
            End If
        End If

        Me.List.Add(aprogress)
        rowControls = rowControls + 1
        HostForm.Controls.Add(aprogress)
        Return aprogress

    End Function

    Public Function AddNewButton(ByVal btnlabel As String, ByVal btntarget As Char, pnt As Point, col As Integer) As System.Windows.Forms.Button

        Dim aButton As New System.Windows.Forms.Button()
        Me.List.Add(aButton)
        HostForm.Controls.Add(aButton)

        If pnt <> Nothing Then
            aButton.Location = pnt
        Else
            'Start the label at the end of the current column
            aButton.Top = Columheight(col) + 20
            aButton.Left = RowWidth(col) + col
            RowWidth(col) = RowWidth(col) + aButton.Width

            If aButton.Height > rowMaxHeight(col) Then
                rowMaxHeight(col) = aButton.Height
            End If
        End If


        aButton.Tag = Me.Count
        rowControls = rowControls + 1
        aButton.AccessibleName = btntarget
        aButton.Text = btnlabel
        AddHandler aButton.Click, AddressOf ClickHandler
        Return aButton
    End Function
    Public Sub Remove()
        ' Check to be sure there is a button to remove.
        If Me.Count > 0 Then
            ' Remove the last button added to the array from the host form 
            ' controls collection. Note the use of the default property in 
            ' accessing the array.
            HostForm.Controls.Remove(Me(Me.Count - 1))
            Me.List.RemoveAt(Me.Count - 1)
        End If
    End Sub

    Public Sub removeall()
        While Me.Count > 0
            HostForm.Controls.Remove(Me(Me.Count - 1))
            Me.List.RemoveAt(Me.Count - 1)
        End While

        For i As Integer = 0 To 680 Step 1
            Columheight(i) = 0
            RowWidth(i) = 0
            rowMaxHeight(i) = 0
            rowControls = 0
        Next


    End Sub
End Class







